package cn.xbtop.blog.realm;

import cn.xbtop.blog.enums.ResultEnum;
import cn.xbtop.blog.exception.BlogException;
import cn.xbtop.blog.pojo.Admin;
import cn.xbtop.blog.service.AdminService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 处理管理员的登录和授权逻辑
 * @author Mxb
 * @version 1.0
 * @date 2020/2/19 20:52
 */
public class AdminRealm extends AuthorizingRealm {

    @Autowired
    private AdminService adminService;

    /**
     * 登录方法
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();

        Admin admin = adminService.selectByUsername(username);
        if (admin == null) {
            //用户不存在
            throw new BlogException(ResultEnum.ERROR.getCode(), "用户不存在！");
        }
        //查询到用户
        return new SimpleAuthenticationInfo(admin, admin.getPassword(), this.getName());
    }

    /**
     * 授权方法
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
}
